package com.woniuxy.shiroinitest;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @BelongsProject: java-85-course-code
 * @BelongsPackage: com.woniuxy.shiroinitest
 * @Author: LiTongMiao
 * @Date: 2022/2/22 19:58
 * @Description: TODO
 */
public class MyRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //这里获取的就是你的用户名！
        String primaryPrincipal = principalCollection.getPrimaryPrincipal()+"";
        //有了用户名，就能去数据库中，找到对应的角色和权限
        //我们随便写几个角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("role1");
        simpleAuthorizationInfo.addRole("role2");
        simpleAuthorizationInfo.addRole("role3");
        simpleAuthorizationInfo.addStringPermission("user:add");
        simpleAuthorizationInfo.addStringPermission("user:update");
        simpleAuthorizationInfo.addStringPermission("user:delete");
        simpleAuthorizationInfo.addStringPermission("user:findOne");
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        //这个密码是 subject.login传进来的！
        String password = new String(usernamePasswordToken.getPassword());
        //通过账号，去数据库进行匹配，查出密码   123456是数据库查出的密码
        if(password.equals("123456")){
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username+"这个就是自定义域封装的对象名！",password,"myRealm");
            //这个凭证 需要交给securityManager，让它帮我管理这个用户登录后的状态和信息！
            return simpleAuthenticationInfo;
        }else{
            throw new AuthenticationException("用户名或密码错误！");
        }
    }
}
